package com.atguigu.service.impl;

import com.atguigu.client.AccountFeignClient;
import com.atguigu.client.OrderFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.config.WxConfig;
import com.atguigu.constant.SystemConstant;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.execption.GuiguException;
import com.atguigu.mapper.PaymentInfoMapper;
import com.atguigu.result.RetVal;
import com.atguigu.service.PaymentInfoService;
import com.atguigu.vo.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 付款信息表 服务实现类
 * </p>
 *
 * @author Joe
 * @since 2024-12-08
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Autowired
    private RSAAutoCertificateConfig config;
    @Autowired
    private WxConfig wxConfig;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Override
    public RetVal<Map<String, Object>> saveOrderAndDetail(String paymentType, String orderNo) {
        try {
            //1.保存一份支付记录-防止扯皮
            PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType, orderNo);
            JsapiServiceExtension service = new JsapiServiceExtension.Builder().config(config).build();
            //2.跟之前下单示例一样，填充预下单参数
            PrepayRequest request = new PrepayRequest();
            Amount amount = new Amount();
            amount.setTotal(1);
            request.setAmount(amount);
            request.setAppid(wxConfig.getAppid());
            request.setMchid(wxConfig.getMerchantId());
            request.setDescription(paymentInfo.getContent());
            request.setNotifyUrl(wxConfig.getNotifyUrl());
            request.setOutTradeNo(orderNo);
            //3.获取用户信息
            //Long userId = AuthContextHolder.getUserId();
            Long userId =15L;
            UserInfoVo userInfoVo = userFeignClient.getUserById(userId).getData();
            Payer payer = new Payer();
            payer.setOpenid(userInfoVo.getWxOpenId());
            request.setPayer(payer);
            //4.response包含了调起支付所需的所有参数，可直接用于前端调起支付
            PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);
            //5.从response中获取页面需要的内容返回给前端
            Map<String, Object> result = new HashMap<>();
            result.put("timeStamp", response.getTimeStamp());
            result.put("nonceStr", response.getNonceStr());
            result.put("package", response.getPackageVal());
            result.put("signType", response.getSignType());
            result.put("paySign", response.getPaySign());
            return RetVal.ok(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuiguException(201, e.getMessage());
        }
    }

    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        PaymentInfo paymentInfo = getOne(new LambdaQueryWrapper<PaymentInfo>().eq(PaymentInfo::getOrderNo,orderNo));
        if(paymentInfo==null){
            paymentInfo=new PaymentInfo();
            //支付订单
            if (paymentType.equals(SystemConstant.PAY_ORDER)) {
                OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
                paymentInfo.setUserId(orderInfo.getUserId());
                paymentInfo.setContent(orderInfo.getOrderTitle());
                paymentInfo.setAmount(orderInfo.getOrderAmount());
            }
//            else{
//                //充值
//                RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
//                paymentInfo.setUserId(rechargeInfo.getUserId());
//                paymentInfo.setContent("充值");
//                paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
//            }
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_UNPAID);
            save(paymentInfo);
        }
        return paymentInfo;
    }
}
